package com.xs.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xs.common.JsonResult;
import com.xs.entity.Comments;
import com.xs.entity.utils.CountAndDayCount;
import com.xs.service.CommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/comment")
public class CommentsController {
    @Autowired
    private CommentsService commentsService;


    /**
     * 新增
     * @param message
     * @return
     */
    @PostMapping
    public JsonResult<?> add(@RequestBody Comments message){
        //说明为新的评论
        if (message.getId()==null){
            message.setTime(new Date());
            if (message.getPid()!=null){//说明为回复
                Integer pid=message.getPid();
                Comments PMessage = commentsService.getById(pid);//查询父级评论
                if(PMessage.getOriginId()!=null){//说明父级之上还有个爷爷级别的  将当前评论设置到爷爷的裙下
                    message.setOriginId(PMessage.getOriginId());//认祖归宗
                }else {
                    message.setOriginId(message.getPid());
                }
            }
        }
        commentsService.save(message);
        return JsonResult.success();
    }


    /**
     * 根据文章id查询文章的评论
     * @param fid
     * @return
     */
    @GetMapping("/tree/{fid}")
    public JsonResult<?> getByaid(@PathVariable Integer fid){
        // 查询所有的评论和回复数据
        List<Comments> messagesDetail = commentsService.findCommentDetail(fid);
        // 查询评论数据（不包括回复）
        List<Comments> originList = messagesDetail.stream().
                filter(message -> message.getOriginId() == null).collect(Collectors.toList());
        System.out.println(originList);

        // 设置评论数据的子节点，也就是回复内容
        for (Comments message : originList) {
            List<Comments> Messages = messagesDetail.stream().filter(message1 -> message.getId().
                    equals(message1.getOriginId())).collect(Collectors.toList());//// 表示回复对象集合


            Messages.forEach(message1 -> {
                Optional<Comments> PMessage = messagesDetail.stream().filter(message2 -> message2.getId().
                        equals(message1.getPid())).findFirst();// 找到当前评论的父级
                PMessage.ifPresent((v->{   // 找到父级评论的用户id和用户昵称，并设置给当前的回复对象
                    message1.setPUserId(v.getUid());
                    message1.setPNickName(v.getNickName());
                }));
            });
            //将originList集合里的评论取出来进行进行排序
            Messages=Messages.stream().sorted(Comparator.comparing(Comments::getId)).collect(Collectors.toList());
            message.setChildren(Messages);
        }


        return JsonResult.success(originList);
    }


    /**
     * 根据id删除消息以及其子消息
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public JsonResult<?> del(@PathVariable Integer id){
        //先删除子评论以及回复
        QueryWrapper<Comments> wrapper= new QueryWrapper<Comments>();
        wrapper.eq("origin_id",id);
        //子评论集合
        List<Comments> list = commentsService.list(wrapper);
        //子评论存在
        if (list!=null) {
            for (Comments message : list) {
                commentsService.removeById(message.getId());
            }
        }
        //删除主评论
        commentsService.removeById(id);
        return JsonResult.success();
    }



    //获取食材评论数以及当日食材的评论数
    @GetMapping("/count")
    public JsonResult<?> countUser() throws ParseException {
        //获取总数量
        List<Comments> row = commentsService.list();
        List<String> time=new ArrayList<>();
        //创建时间转换器
        DateFormat df = new SimpleDateFormat("YYYY-MM-dd");
        for (Comments user : row) {
            String format = df.format(user.getTime());
            time.add(format);
        }
        System.out.println(time);
        Date date = new Date();
        //获取当前时间的年月日
        String data = df.format(date);
        int count=0;

        for (String s : time) {
            if (s.equals(data)){
                count=count+1;
            }
        }

        //将数据打包
        CountAndDayCount rows=new CountAndDayCount();
        rows.setCount(commentsService.count());
        rows.setDayCount(count);
        return JsonResult.success(rows);
    }
}
